package beautiful.butterfly.server.httpserver.mvc.core.ioc;

import beautiful.butterfly.server.httpserver.mvc.core.WebContent;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;


/**
 * 为控制器注入无状态接口对象
 */
public class IOCManage {
    public static void injectById(Class<?> clazz, Object object) {
        ApplicationContext applicationContext = WebContent.getWebApplicationContext();
        Field[] fields = clazz.getDeclaredFields();
        int length = fields.length;
        // 遍历所有属性
        if (length != 0) {
            for (int j = 0; j < length; j++) {
                Field field = fields[j];
                ById byId = field.getAnnotation(ById.class);
                if (byId != null) {
                    String value = byId.value();
                    if (value == null) {
                        throw new NullPointerException("byName value");
                    }
                    // 检查field 和 object的类型是否一样
                    Object bean = applicationContext.getBean(value);
                    if (!(field.getType().isAssignableFrom(bean.getClass()))) {
                        throw new RuntimeException("从Spring获得的对象不是接口或者父类的子类实例");
                    }
                    field.setAccessible(true);
                    try {
                        field.set(object, bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    }
                }

            }

        }

    }
}
